#!/usr/bin/python
import time
import discord
import os

from mcstatus import MinecraftServer

from discord.ext import commands

server = MinecraftServer.lookup("YOURSERVER.COM")
try:
    status = server.status()
    print("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency))
except:
    print("Server offline")

client = commands.Bot(command_prefix = ".")

@client.event
async def on_ready():
    print("Ready")
    
@client.command()
async def server_start(ctx):
    print("Starting server")
    try:
        status = server.status()
        print("```css\nThe server is already running")
        await ctx.send("```css\nThe server is already running\n```")
    except:
        await ctx.send('Starting minecraft server. Please wait a few seconds...')
        os.system("cd /home/$USER/ && nohup java -Xmx2048M -Xms2048M -jar server.jar nogui &")
        time.sleep(7)
        await ctx.send("```css\nServer started\nAddress: YOURSERVER.COM```")
        
    
    
@client.command()
async def server_status(ctx):
    print("Server status requested.")
    try:
        status = server.status()
        print("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency))
        await ctx.send("**Server status**\n```diff\n+ Players: {0} \n+ Latency: {1} ms```".format(status.players.online, status.latency))
    except:
        await ctx.send("**Server status**\n```diff\n- Server is offline\n```")
    
@client.command()
async def server_stop(ctx):
    print("Server shutdown requested.")
    try:
        status = server.status()
        if status.players.online !=0:
            await ctx.send("**Server shutdown requested:**\n```diff\n- Sorry. server can only be shutdown if no one is playing.\nPlayers: {0}```".format(status.players.online))
        else:
            await ctx.send("**Server shutdown requested:**\n```diff\n+ Server sucessfully shut down.```")
            os.system("killall java")
    except:
        await ctx.send('```diff\n- Server is not running\n```')
    
    status = server.status()
    
@client.command()
async def server_help(ctx):
    print("Server shutdown requested.")
    await ctx.send("```css\nMinecraft server controller\nBy AyyZee\nWritten in python\n```\n```arm\nCOMMAND : WHAT HAPPENS\n```\n```arm\n.server_help : Show this message.\n\n.server_start : Starts the minecraft server, playable after 5 to 10 seconds.\n\n.server_status : Shows player numbers & latency or whether the server is offline.\n\n.server_stop : Stops the server only when no one is playing.\n```\n```fix\nServer address = YOURSERVER.COM```")
    

client.run('YOUR DISCORD API KEY')
